import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:model_maker/checkbox_with_text.dart';
import 'package:model_maker/configurations_model.dart';
import 'package:model_maker/string_utils.dart';
import 'package:provider/provider.dart';

class FunctionsAppBar extends StatefulWidget {
  const FunctionsAppBar({super.key});

  @override
  State<FunctionsAppBar> createState() => _FunctionsAppBarState();
}

class _FunctionsAppBarState extends State<FunctionsAppBar> {
  var textEditingController = TextEditingController();
  late ConfigurationsModel _confModel;
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _confModel = context.read<ConfigurationsModel>();
    _confModel.setIsMateChanged((value) {
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    final confModel = Provider.of<ConfigurationsModel>(context, listen: false);
    confModel.uploadIsMate();

    final buttonWidth = 90.0;

    /// 粘贴按钮
    final pasteWidget = Padding(
      padding: EdgeInsets.all(4),
      child: MaterialButton(
        onPressed: () {
          _readClipboard().then((value) {
            confModel.pastedJsonString = value ?? "";
          });
        },
        color: Colors.redAccent,
        height: 100,
        minWidth: buttonWidth,
        child: const Icon(Icons.paste),
      ),
    );

    final inputNameWidget = Container(
      child: Padding(
        padding: EdgeInsets.all(4),
        child: Container(
          color: Colors.yellowAccent,
          child: Padding(
            padding: EdgeInsets.all(6),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 1),
                Text('配置模型名称:', style: TextStyle(fontSize: 16)),
                SizedBox(height: 4),
                Container(
                  color: Colors.white60,
                  child: Padding(
                    padding: EdgeInsets.fromLTRB(6, 1, 6, 1),
                    child: TextField(
                      maxLines: 1,
                      decoration: InputDecoration(
                        hintText: "请输入根模型名，默认Root",
                        hintStyle: TextStyle(color: Colors.grey),
                        border: InputBorder.none,
                      ),
                      controller: textEditingController,
                      onChanged: (value) {
                        setState(() {
                          confModel.modelName = value;
                        });
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );

    /// 中间内容
    final centerContent = Wrap(
      spacing: 8,
      runSpacing: 8,
      children: [
        Container(
          constraints: BoxConstraints(maxWidth: 140),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              CheckboxWithText(
                text: '使用驼峰命名',
                value: confModel.isCamelCase,
                onChanged: (value) {
                  setState(() {
                    confModel.isCamelCase = value ?? true;
                  });
                },
              ),
              CheckboxWithText(
                text: '使用结构体',
                value: confModel.isUsingStruct,
                onChanged: (value) {
                  setState(() {
                    confModel.isUsingStruct = value ?? true;
                  });
                },
              ),
              CheckboxWithText(
                text: '支持Objc',
                value: confModel.supportObjc,
                onChanged: (value) {
                  setState(() {
                    confModel.supportObjc = value ?? true;
                  });
                },
              ),
            ],
          ),
        ),
        Container(
          constraints: BoxConstraints(maxWidth: 185),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              CheckboxWithText(
                text: '支持SmartCodable',
                value: confModel.supportSmartCodable,
                onChanged: (value) {
                  setState(() {
                    confModel.supportSmartCodable = value ?? true;
                  });
                },
              ),
              CheckboxWithText(
                text: '原生Codable',
                value: confModel.originCodable,
                onChanged: (value) {
                  setState(() {
                    confModel.originCodable = value ?? true;
                  });
                },
              ),
              CheckboxWithText(
                text: '(Smart)Codable映射',
                value: confModel.codableMap,
                onChanged: (value) {
                  setState(() {
                    confModel.codableMap = value ?? true;
                  });
                },
              ),
            ],
          ),
        ),
        Container(
          constraints: BoxConstraints(maxWidth: 170),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              CheckboxWithText(
                text: '支持YYModel',
                value: confModel.supportYYModel,
                onChanged: (value) {
                  setState(() {
                    confModel.supportYYModel = value ?? true;
                  });
                },
              ),
              CheckboxWithText(
                text: '支持public',
                value: confModel.supportPublic,
                onChanged: (value) {
                  setState(() {
                    confModel.supportPublic = value ?? true;
                  });
                },
              ),
              CheckboxWithText(
                text: '反序列化静态方法',
                value: confModel.objcObjcDeserialization,
                onChanged: (value) {
                  setState(() {
                    confModel.objcObjcDeserialization = value ?? true;
                  });
                },
              ),
            ],
          ),
        ),
        Container(
          constraints: BoxConstraints(maxWidth: 140),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              CheckboxWithText(
                text: 'Mate项目',
                value: confModel.isMate,
                onChanged: (value) {
                  setState(() {
                    confModel.isMate = value ?? false;
                  });
                },
              ),
              CheckboxWithText(
                text: '生成构造方法',
                value: confModel.supportConstruction,
                onChanged: (value) {
                  setState(() {
                    confModel.supportConstruction = value ?? false;
                  });
                },
              ),
            ],
          ),
        ),
      ],
    );

    /// 复制按钮
    final copyWidget = Padding(
      padding: EdgeInsets.all(4),
      child: MaterialButton(
        onPressed: () {
          _copyToClipboard(context, outputResult ?? "");
        },
        color: Colors.greenAccent,
        height: 100,
        minWidth: buttonWidth,
        child: const Icon(Icons.copy),
      ),
    );

    return LayoutBuilder(
      builder: (context, constraints) {
        final double containerWidth = constraints.maxWidth;
        final double minContainerWidth = 1080;
        if (containerWidth > minContainerWidth) {
          return Container(
            width: double.infinity,
            color: Colors.blueGrey,
            child: Padding(
              padding: EdgeInsets.all(8),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  pasteWidget,
                  SizedBox(width: 240, height: 100, child: inputNameWidget),
                  centerContent,
                  Spacer(),
                  copyWidget,
                ],
              ),
            ),
          );
        } else {
          return Container(
            width: double.infinity,
            color: Colors.blueGrey,
            child: Padding(
              padding: EdgeInsets.all(8),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      pasteWidget,
                      Expanded(child: inputNameWidget),
                      copyWidget,
                    ],
                  ),
                  centerContent,
                ],
              ),
            ),
          );
        }
      },
    );
  }

  /// 将文本复制到剪贴板
  void _copyToClipboard(BuildContext context, String text) async {
    await Clipboard.setData(ClipboardData(text: text));

    var hint = "复制成功！";
    var todosCount = StringUtils.countofTodo(text);
    if (todosCount > 0) {
      hint += "注意有$todosCount处TODO项,可能是未识别类型，为避免出现程序崩溃或取不到值的情况，请手动处理";
      _showDialog(context, hint);
    } else {
      // 显示复制成功的提示
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(hint), duration: Duration(seconds: 1)),
      );
    }
  }

  /// 读取剪切板
  Future<String?> _readClipboard() async {
    try {
      // 获取剪贴板数据
      final clipboardData = await Clipboard.getData(Clipboard.kTextPlain);
      if (clipboardData != null && clipboardData.text != null) {
        // 显示成功提示
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('已粘贴剪贴板内容'), duration: Duration(seconds: 1)),
        );
        return clipboardData.text ?? "";
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('剪贴板为空'), duration: Duration(seconds: 1)),
        );
        return null;
      }
    } catch (e) {
      // 处理异常
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('读取剪贴板失败: $e'), duration: Duration(seconds: 1)),
      );
      return null;
    }
  }

  /// 显示弹窗
  void _showDialog(BuildContext context, String message) {
    showDialog(
      context: context,
      builder:
          (context) => Dialog(
            insetPadding: const EdgeInsets.symmetric(horizontal: 24),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16.0),
            ),
            child: ConstrainedBox(
              constraints: const BoxConstraints(maxWidth: 400),
              child: Padding(
                padding: const EdgeInsets.fromLTRB(24, 28, 24, 20),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '温馨提示',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.w600,
                        color: Colors.black87,
                      ),
                    ),
                    const SizedBox(height: 16),
                    Text(
                      message,
                      style: TextStyle(
                        fontSize: 16,
                        height: 1.5,
                        color: Colors.black54,
                      ),
                    ),
                    const SizedBox(height: 28),
                    Center(
                      child: SizedBox(
                        width: double.infinity,
                        child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.blue,
                            foregroundColor: Colors.white,
                            padding: const EdgeInsets.symmetric(vertical: 14),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(10),
                            ),
                            elevation: 0,
                          ),
                          onPressed: () => Navigator.pop(context),
                          child: const Text(
                            '我知道了',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
    );
  }
}
